package com.raymond.httpclient.proxy;

import com.raymond.httpclient.HttpClientFactory;
import com.raymond.httpclient.cache.ServerAddressCache;
import com.raymond.httpclient.cache.ServerCaches;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 服务代理对象
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-04-01 11:05
 */
public class HttpServerProxy<T> implements InvocationHandler {

    private static final String VOID_STR = "void";

    private ServerCaches serverCaches;

    private HttpClient httpClient;

    private T obj;

    public HttpServerProxy(ServerCaches serverCaches) {
        this.serverCaches = serverCaches;
        obj = (T) Proxy.newProxyInstance(HttpServerProxy.class.getClassLoader(), new Class[]{serverCaches.getClassType()}, this);
    }

    public T getObj() {
        return this.obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        ServerCaches.MethodCache methodCache = serverCaches.getMethodCache(method.getName());
        HttpUriRequest httpRequest = HttpClientFactory.getHttpUriRequest(getAddress() + methodCache.url, args[0], methodCache.httpMethod);
        HttpClientFactory.setHeader(httpRequest, methodCache.headers);
        if (httpClient == null) {
            httpClient = HttpClientFactory.getHttpClient();
        }
        String result = HttpClientFactory.execute(httpClient, httpRequest);
        if (VOID_STR.equals(methodCache.returnType.getName())) {
            return null;
        }
        return HttpClientFactory.resultStr(result, methodCache.returnType);
    }

    private String getAddress() {
        return ServerAddressCache.getAddress(serverCaches.getServerName());
    }
}
